/**
 * Auto Discovery Service
 */

import { Config, MCPServer, ServerConfig } from '../types';
import { Logger } from '../utils/logger';

export class AutoDiscovery {
  private logger = new Logger('AutoDiscovery');

  constructor(private config: Config) {}

  async discover(): Promise<MCPServer[]> {
    this.logger.info('Starting server discovery...');
    
    const servers: MCPServer[] = [];
    
    // Add configured servers
    for (const [id, serverConfig] of Object.entries(this.config.servers)) {
      if (serverConfig.enabled) {
        servers.push(this.createServer(id, serverConfig));
      }
    }
    
    // Auto-discover if enabled
    if (this.config.discovery.enabled) {
      const discovered = await this.autoDiscover();
      servers.push(...discovered);
    }
    
    this.logger.info(`Discovered ${servers.length} servers`);
    return servers;
  }

  private createServer(id: string, config: ServerConfig): MCPServer {
    return {
      id,
      name: config.metadata?.name || id,
      description: config.metadata?.description,
      config,
      status: 'stopped'
    };
  }

  private async autoDiscover(): Promise<MCPServer[]> {
    const servers: MCPServer[] = [];
    
    // Basic discovery - look for common MCP servers
    const commonServers = [
      {
        id: 'filesystem',
        name: 'Filesystem Server',
        command: 'mcp-server-filesystem'
      },
      {
        id: 'shell',
        name: 'Shell Server', 
        command: 'mcp-server-shell'
      }
    ];
    
    for (const serverInfo of commonServers) {
      // Check if command exists (simplified)
      const serverConfig: ServerConfig = {
        enabled: true,
        command: serverInfo.command,
        metadata: {
          name: serverInfo.name
        }
      };
      
      servers.push(this.createServer(serverInfo.id, serverConfig));
    }
    
    return servers;
  }
}